<template>
  <el-card class="post-card">
    <div class="card-header">
      <h2 class="card-title">全部帖子</h2>
    </div>
    <div class="toolbar">
      <el-input 
        v-model="searchQuery" 
        placeholder="搜索帖子标题或内容" 
        clearable 
        class="search-input" 
        @input="handleSearchInput"
        @change="handleSearch"
      >
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input>
    </div>

    <el-table :data="posts" style="width: 100%" v-loading="loading">
      <el-table-column prop="title" label="标题" min-width="180">
        <template #default="scope">
          <div class="truncate-text">{{ scope.row.title }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="内容" min-width="250">
        <template #default="scope">
          <div class="truncate-text">{{ scope.row.content }}</div>
        </template>
      </el-table-column>
      <el-table-column label="作者" width="120">
        <template #default="scope">
          <el-tag>{{ scope.row.username || scope.row.author }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="likes_count" label="点赞数" width="80" />
      <el-table-column label="发帖时间" width="160">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="最后更新" width="160">
        <template #default="scope">
          {{ formatDate(scope.row.updated_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            type="text" 
            size="small" 
            @click="handleDelete(scope.row)"
            :style="{ color: '#f56c6c' }"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination 
        v-model:current-page="currentPage" 
        v-model:page-size="pageSize" 
        :total="total"
        :page-sizes="[10, 20, 50, 100]" 
        layout="total, sizes, prev, pager, next, jumper" 
        @size-change="handleSizeChange"
        @current-change="handlePageChange" 
      />
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import nework from '../../api/index'

const { communityApi, request } = nework
const searchQuery = ref('')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const posts = ref([])

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 处理搜索输入（带防抖）
const handleSearchInput = debounce(() => {
  if (searchQuery.value.trim() === '') {
    handleSearch()
  }
}, 300)

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchData()
}

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchData()
}

// 处理编辑帖子
const handleEdit = (post) => {
  console.log('编辑帖子:', post)
  // 这里可以实现编辑逻辑，例如跳转到编辑页面或打开编辑对话框
}

// 处理删除帖子
const handleDelete = async (post) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除帖子 "${post.title}" 吗？此操作不可恢复！`,
      '警告',
      {
        type: 'error',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    
    loading.value = true
    try {
      // 这里应该调用删除API
      // await request(communityApi.deletePost, { postId: post.postId })
      
      // 临时模拟删除成功 - 实际应该调用API
      posts.value = posts.value.filter(p => p.postId !== post.postId)
      ElMessage.success('帖子删除成功')
      
      // 如果当前页没有数据了且不是第一页，则回到上一页
      if (posts.value.length === 0 && currentPage.value > 1) {
        currentPage.value--
        fetchData()
      }
    } catch (error) {
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  } catch {
    // 用户取消操作
  }
}

// 获取数据的统一方法
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 如果有搜索关键词，添加到请求参数
    if (searchQuery.value.trim()) {
      params.keyword = searchQuery.value.trim()
    }
    
    const res = await request(communityApi.getCommunityList, params)
    
    if (res && res.code === 0 && res.data) {
      // 根据实际返回的数据结构进行解析
      posts.value = res.data.data || []
      
      // 从分页信息中获取总数
      if (res.data.pagination) {
        currentPage.value = parseInt(res.data.pagination.currentPage) || 1
        pageSize.value = parseInt(res.data.pagination.pageSize) || 10
        
        // 如果API返回了总数，使用API返回的总数
        // 如果没有返回总数，则根据是否有更多数据来估算总数
        if (res.data.pagination.total) {
          total.value = parseInt(res.data.pagination.total)
        } else if (res.data.pagination.hasMore === false) {
          total.value = posts.value.length + (currentPage.value - 1) * pageSize.value
        } else {
          // 如果有更多数据，至少还有一页
          total.value = posts.value.length + (currentPage.value - 1) * pageSize.value + pageSize.value
        }
      } else {
        total.value = posts.value.length
      }
    } else {
      posts.value = []
      total.value = 0
      ElMessage.warning(res?.msg || '获取数据失败')
    }
  } catch (error) {
    posts.value = []
    total.value = 0
    ElMessage.error('获取数据出错：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
// 主题颜色
$primary-color: #409eff;
$primary-light: #ecf5ff;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$info-color: #909399;
$background-color: #f5f7fa;
$text-color: #303133;
$text-secondary: #606266;
$text-light: #909399;
$border-color: #dcdfe6;

.post-card {
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .card-header {
    margin-bottom: 20px;

    .card-title {
      margin: 0;
      font-size: 22px;
      font-weight: 600;
      color: $text-color;
      position: relative;
      padding-left: 12px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 20px;
        background: linear-gradient(to bottom, $primary-color, lighten($primary-color, 10%));
        border-radius: 2px;
      }
    }
  }

  .toolbar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    .search-input {
      width: 300px;
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .truncate-text {
    max-width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

// 响应式调整
@media screen and (max-width: 768px) {
  .post-card {
    padding: 15px;
    
    .toolbar .search-input {
      width: 100%;
    }
    
    .pagination {
      justify-content: center;
    }
  }
}
</style>